<?php

namespace backend\modules\Sys\modules\BeMenu\controllers;

use backend\models\c2\search\rest\BeMenuSearch;
use common\models\c2\entity\BeMenu;
use common\models\c2\statics\EntityModelStatus;
use common\rest\controllers\AuthController;

use common\rest\models\c2\statics\ResponseDatum;
use Yii;
use yii\web\NotFoundHttpException;

/**
 * Default controller for the `be-menu` module
 */
class DefaultController extends AuthController
{
    public $modelClass = 'common\models\c2\entity\BeMenu';

    // public $modelClass = 'common\models\c2\search\BeMenuSearch';

    public function actionIndex()
    {
        return ResponseDatum::getSuccessDatum($this->formatMenus());
    }

    /**
     * Renders the index view for the module
     * @param null $id
     * @return array
     * @throws NotFoundHttpException
     * @throws \yii\web\NotAcceptableHttpException
     */
    public function actionEdit($id = null)
    {
        /** @var BeMenu $model */
        $model = $this->retrieveModel($id);

        if ($model->load(Yii::$app->request->post())) {
            if ($model->save()) {
                return ResponseDatum::getSuccessDatum(['model' => $model, 'parents' => $model->getParents()]);
            } else {
                return ResponseDatum::getErrorDatum(['model' => $model->errors, 'parents' => $model->getParents()]);
            }
        }
        return ResponseDatum::getSuccessDatum(['model' => $model, 'parents' => $model->getParents()]);
    }

    /**
     * Finds the BeMenu model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return array|BeMenu
     * @throws NotFoundHttpException
     */
    protected function findModel($id)
    {
        if (($model = BeMenu::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    public function actionAvailable($status = null)
    {
        if (!in_array($status, array_keys(EntityModelStatus::getData()))) {
            return false;
        }
        $params = Yii::$app->request->post();
        $ids = isset($params['ids']) ? $params['ids'] : [];
        $count = BeMenu::updateAll(['status' => $status], ['in', 'id', $ids]);
        if ($count) {
            return ResponseDatum::getSuccessDatum($this->formatMenus());
        }
        return ResponseDatum::getErrorDatum($count);
    }

    /**
     * @return array
     * @throws NotFoundHttpException
     * @throws \Throwable
     * @throws \yii\db\StaleObjectException
     */
    public function actionDelete()
    {
        $params = Yii::$app->request->post();
        $id = isset($params['id']) ? $params['id'] : 0;
        /** @var BeMenu $model */
        $model = $this->retrieveModel($id);
        $count = $model->delete();
        if ($count) {
            return ResponseDatum::getSuccessDatum($this->formatMenus());
        }
        return ResponseDatum::getErrorDatum($count);
    }

    public function formatMenus()
    {
        $items = BeMenuSearch::find()
            // ->select(['id', 'parent_id', 'name', 'label', 'icon', 'path'])
            ->orderBy(['position' => SORT_ASC])
            // ->where(['status' => EntityModelStatus::STATUS_ACTIVE])
            ->asArray()->all();
        $data = [];
        foreach ($items as $item) {
            $this->reserve($item);
            if ($item['parent_id'] == 0) {
                $item['children'] = [];
                foreach ($items as $item1) {
                    $this->reserve($item1);
                    if ($item['id'] == $item1['parent_id']) {
                        $item['children'][] = $item1;
                    }
                }
                $data[] = $item;
            }
        }
        return $data;
    }

    public function reserve(&$item)
    {
        $item['id'] = (int)$item['id'];
        $item['parent_id'] = (int)$item['parent_id'];
        $item['status'] = (int)$item['status'];
        $item['position'] = (int)$item['position'];
    }

}
